<template>
    <div class="width1200 margin0auto bgWhite">
        <el-row>
            <el-col :span="20" :offset="2">
                <h1 class="borderLeft paddingLeft15">{{this.initStatus}}{{this.headTitle}}</h1>
            </el-col>
            <el-col :span="20" :offset="2">
                <el-form
                    :model="ruleForm"
                    :rules="rules"
                    ref="ruleForm"
                    label-width="100px"
                    class="demo-ruleForm"
                >
                    <el-form-item label="案例负责人" prop="contactId">
                        <el-input v-model="ruleForm.contactId"></el-input>
                    </el-form-item>
                    <el-form-item label="案例介绍" prop="content">
                        <div class="edit_container">
                            <!-- <quill-editor 
                                v-model="ruleForm.content" 
                                ref="myQuillEditor" 
                                :options="editorOption" 
                                @blur="onEditorBlur($event)" @focus="onEditorFocus($event)"
                                @change="onEditorChange($event)">
                            </quill-editor>-->
                            <!-- 图片上传组件辅助-->
                            <el-upload
                                class="avatar-uploader"
                                :action="serverUrl"
                                name="file"
                                :show-file-list="false"
                                :on-success="uploadSuccess"
                                :on-error="uploadError"
                                :before-upload="beforeUpload"
                            ></el-upload>
                            <!--富文本编辑器组件-->
                            <el-row v-loading="quillUpdateImg">
                                <quill-editor
                                    v-model="content"
                                    ref="myQuillEditor"
                                    :options="editorOption"
                                    @change="onEditorChange($event)"
                                    @ready="onEditorReady($event)"
                                ></quill-editor>
                            </el-row>
                        </div>
                        <!-- 富文本结束 -->
                    </el-form-item>
                    <el-form-item label="排序号" prop="idx">
                        <el-input v-model="ruleForm.idx"></el-input>
                    </el-form-item>
                    <el-form-item label="发布时间" prop="pdate">
                        <div class="block">
                            <el-date-picker v-model="ruleForm.pdate" type="date" placeholder="选择日期"></el-date-picker>
                        </div>
                    </el-form-item>
                    <el-form-item label="状态" prop="stateCode">
                        <el-select v-model="ruleForm.stateCode" placeholder="请选择" disabled>
                            <el-option
                                v-for="item in options"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                            ></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="案例名称" prop="name">
                        <el-input v-model="ruleForm.name"></el-input>
                    </el-form-item>
                    <el-form-item label="专业类型标签" prop="professionTags">
                        <el-input v-model="ruleForm.professionTags" placeholder="请用英文逗号隔开标识分隔"></el-input>
                    </el-form-item>
                    <el-form-item label="项目类型标签" prop="projectTags">
                        <el-input v-model="ruleForm.projectTags" placeholder="请用英文逗号隔开标识分隔"></el-input>
                    </el-form-item>
                    <el-form-item label="项目地址" prop="projectAddressId">
                        <el-input v-model="ruleForm.projectAddressId" placeholder="请带http://"></el-input>
                    </el-form-item>
                    <el-form-item label="成功案例简介" prop="summary">
                        <el-input type="textarea" v-model="ruleForm.summary"></el-input>
                    </el-form-item>
                    <el-form-item label="缩略图" prop="thumb">
                        <el-upload
                            :action="uploadUrl()"
                            list-type="picture-card"
                            :on-preview="handlePictureCardPreview"
                            :on-success="successUpload"
                            :limit="1"
                            :on-remove="handleRemove"
                        >
                            <i class="el-icon-plus"></i>
                        </el-upload>
                        <el-dialog :visible.sync="dialogVisible">
                            <img width="100%" :src="dialogImageUrl" alt="">
                        </el-dialog>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="submitForm('ruleForm')">立即创建</el-button>
                        <el-button @click="resetForm('ruleForm')">重置</el-button>
                    </el-form-item>
                </el-form>
            </el-col>
        </el-row>
    </div>
</template>
<script>
import { serverBaseUrl } from "src/common/setting";
import { quillEditor } from "vue-quill-editor"; //调用编辑器

const toolbarOptions = [
  ["bold", "italic", "underline", "strike"], // toggled buttons
  ["blockquote", "code-block"],

  [{ header: 1 }, { header: 2 }], // custom button values
  [{ list: "ordered" }, { list: "bullet" }],
  [{ script: "sub" }, { script: "super" }], // superscript/subscript
  [{ indent: "-1" }, { indent: "+1" }], // outdent/indent
  [{ direction: "rtl" }], // text direction

  [{ size: ["small", false, "large", "huge"] }], // custom dropdown
  [{ header: [1, 2, 3, 4, 5, 6, false] }],

  [{ color: [] }, { background: [] }], // dropdown with defaults from theme
  [{ font: [] }],
  [{ align: [] }],
  ["link", "image", "video"],
  ["clean"] // remove formatting button
];

export default {
  name: "EditPage",
  data() {
    var checkWebsite = (rule, value, callback) => {
      let websiteReg = /^([hH][tT]{2}[pP]:\/\/|[hH][tT]{2}[pP][sS]:\/\/)(([A-Za-z0-9-~]+)\.)+([A-Za-z0-9-~\/])+$/;
      if (value === "") {
        callback(new Error("请输入网址"));
      } else if (websiteReg.test(value)) {
        callback();
      } else {
        callback(new Error("网址格式不正确，请带http://"));
      }
    };
    return {
      quillUpdateImg: false, // 根据图片上传状态来确定是否显示loading动画，刚开始是false,不显示
      serverUrl: { serverBaseUrl }.serverBaseUrl + "/admin/upload", // 这里写你要上传的图片服务器地址
      header: {token: sessionStorage.token},  // 有的图片服务器要求请求头需要有token之类的参数，写在这里
      content: "", // 富文本内容
      editorOption: {
        placeholder: "",
        theme: "snow", // or 'bubble'
        modules: {
          toolbar: {
            container: toolbarOptions, // 工具栏
            handlers: {
              image: function(value) {
                if (value) {
                  document.querySelector(".avatar-uploader input").click();
                } else {
                  this.quill.format("image", false);
                }
              }
            }
          }
        }
      }, // 富文本编辑器配置

      content: "",
      a_content: "",
      // editorOption: {},

      timeVal: "", //日期

      options: [
        {
          value: "1",
          label: "新建"
        },
        {
          value: "2",
          label: "待审核"
        },
        {
          value: "3",
          label: "未发布"
        },
        {
          value: "4",
          label: "已发布"
        }
      ],
      select: "",

      initStatus: "", //新增/编辑
      headTitle: "", //标题/服务设备
      dialogImageUrl: "",
      dialogVisible: false,
      thumb: "",
      ruleForm: {},
      rules: {
        name: [
          { required: true, message: "案例名称不能为空", trigger: "blur" }
        ],
        projectAddressId: [{ trigger: "blur", validator: checkWebsite }]
      }
    };
  },
  components: {
    quillEditor
  },
  mounted() {
    this.initData();
  },
  methods: {
    // 富文本图片上传前
    beforeUpload() {
      // 显示loading动画
      this.quillUpdateImg = true;
    },

    uploadSuccess(res, file) {
      // res为图片服务器返回的数据
      // 获取富文本组件实例
      let quill = this.$refs.myQuillEditor.quill;
      // 如果上传成功
      if (res.code === 0 && res.info !== null) {
        // 获取光标所在位置
        let length = quill.getSelection().index;
        // 插入图片  res.info为服务器返回的图片地址
        quill.insertEmbed(
          length,
          "image",
          { serverBaseUrl }.serverBaseUrl + "/" + res.data
        );
        // 调整光标到最后
        quill.setSelection(length + 1);
      } else {
        this.$message.error("图片插入失败");
      }
      // loading动画消失
      this.quillUpdateImg = false;
    },

    // 富文本图片上传失败
    uploadError() {
      // loading动画消失
      this.quillUpdateImg = false;
      this.$message.error("图片插入失败");
    },

    async initData() {

console.log(this.$route.query.tabStatus)



//获取tabStatus,判断接口权限

      const { $api } = this;
      var dataObj = {
        id: this.$route.query.id
      };
          const resData = await $api.user.apiCorpCasesDetail(dataObj);
      if (resData.code == 0) {
        this.ruleForm = resData.data;
        let stateCode = resData.data.stateCode;
        if (stateCode == 1) {
          this.select = "新建";
        } else if (stateCode == 2) {
          this.select = "待审核";
        } else if (stateCode == 3) {
          this.select = "未发布";
        } else {
          this.select = "已发布";
        }
        // this.select = resData.data.stateCode;
        // console.log(resData);
      } else {
        this.$message.error(resData.msg);
      }
    },
    //点击提交
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.subFormData(this.ruleForm);
        } else {
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    //提交表单数据
    async subFormData(dataObj) {
      const { $api } = this;
      let tabStatus = this.$route.query.tabStatus;
         if(tabStatus == "solution"){
         const resData = await $api.user.apiCorpSolutionCu(dataObj);
      }else if(tabStatus == "succseeCase"){
         const resData = await $api.user.apiCorpCaseCu(dataObj);
      }else if(tabStatus == "projectServices"){
         const resData = await $api.user.apiCorpProjectCu(dataObj);
      }else if(tabStatus == "commodity"){
         const resData = await $api.user.piCorpDeviceCu(dataObj);
      }
      
      if (resData.code == 0) {
        if (resData.code == 0) {
          this.$message.success("编辑成功");
          this.$router.go(-1);
        } else {
          this.$message.error(resData.msg);
        }
      } else {
        this.$message.error(resData.msg);
        // location.reload();
      }
    },
    handleRemove(file, fileList) {},
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    uploadUrl() {
      return { serverBaseUrl }.serverBaseUrl + "/admin/upload";
    },
    //成功上传
    successUpload(response, file, fileList) {
      this.thumb = response.data;
    },
    //富文本
    onEditorReady(editor) {
      console.log(editor);
    },
    onEditorBlur() {}, // 失去焦点事件
    onEditorFocus() {}, // 获得焦点事件
    onEditorChange() {}, // 内容改变事件
    // 转码
    escapeStringHTML(str) {
      str = str.replace(/</g, "<");
      str = str.replace(/>/g, ">");
      return str;
    }
  },
  computed: {
    editor() {
      return this.$refs.myQuillEditor.quill;
    }
  }
};
</script>
